package com.platform.common.util;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver;
import com.thoughtworks.xstream.io.json.JsonWriter;

import java.io.Writer;

/**
 * Created with IntelliJ IDEA.
 * User: wangyanginfo
 * Date: 12-9-7
 * Time: 下午2:26
 * To change this template use File | Settings | File Templates.
 */
public class JSONUtil {

    /**
     * 将对象传换成JSON格式字符串
     *
     * @param obj 对象
     * @return JSON格式字符串
     */
    public final static String objectToJSON(Object obj) {
        XStream xstream = new XStream(new JettisonMappedXmlDriver());
        xstream.setMode(XStream.NO_REFERENCES);
        return xstream.toXML(obj);
    }

    /**
     * 将对象传换成JSON格式字符串
     *
     * @param obj         对象
     * @param alias       别名
     * @param cas         需要进行名字转换的Class
     * @param isRootTitle 是否删除根节点
     * @return JSON格式字符串
     */
    public final static String objectToJSON(Object obj, String alias, Class cas, boolean isRootTitle) {
        JsonHierarchicalStreamDriver driver = new JsonHierarchicalStreamDriver();
        XStream xstream = new XStream(driver);
        xstream.alias("rows", cas);
        //xstream.alias(alias, obj.getClass());
        //是否删除根节点
        if (isRootTitle) {
            //删除根节点
            xstream = new XStream(new JsonHierarchicalStreamDriver() {
                public HierarchicalStreamWriter createWriter(Writer out) {
                    return new JsonWriter(out, JsonWriter.DROP_ROOT_MODE);
                }
            });
        }
        return xstream.toXML(obj);
    }

    /**
     * 将对象传换成JSON格式字符串
     *
     * @param obj         对象
     * @param alias       别名
     * @param isRootTitle 是否删除根节点
     * @return JSON格式字符串
     */
    public final static String objectToJSON(Object obj, String alias, boolean isRootTitle) {
        return objectToJSON(obj, alias, obj.getClass(), isRootTitle);
    }

    /**
     * 将对象传换成JSON格式字符串
     *
     * @param obj 对象
     * @return JSON格式字符串
     */
    public final static String objectToJSON(Object obj, boolean isRootTitle) {
        String packageClassName = obj.getClass().getName();
        //获取类名（不带包名）
        String alias = packageClassName.substring(packageClassName.lastIndexOf(".") + 1, packageClassName.length());
        return objectToJSON(obj, alias, isRootTitle);
    }

}
